package com.fts.fts.fitness_tracking_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fts.fts.fitness_tracking_system.mapper.FitnessGoalsMapper;
import com.fts.fts.fitness_tracking_system.pojo.FitnessGoals;
import com.fts.fts.fitness_tracking_system.pojo.Notifications;
import com.fts.fts.fitness_tracking_system.service.NotificationsService;
import com.fts.fts.fitness_tracking_system.mapper.NotificationsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.relational.core.sql.In;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author huawei
* @description 针对表【notifications】的数据库操作Service实现
* @createDate 2025-02-11 14:14:00
*/
@Service
@Slf4j
public class NotificationsServiceImpl extends ServiceImpl<NotificationsMapper, Notifications>
    implements NotificationsService{
    private static final String MESSAGE_COMPLETED = "恭喜您已完成健身目标！";
    private static final String MESSAGE_CLOSE = "您已接近健身目标，加油！";
    @Autowired
    private NotificationsMapper notificationsMapper;
    @Autowired
    private FitnessGoalsMapper fitnessGoalsMapper;
    @Override
    public List<Notifications> getNotificationsByUserId(Integer userId) {
        checkGoalProgress(userId);
        return notificationsMapper.selectList(new QueryWrapper<Notifications>().eq("user_id",userId));
    }
    public void checkGoalProgress(Integer userId) {
        List<FitnessGoals> fitnessGoalsList = fitnessGoalsMapper.selectList(new QueryWrapper<FitnessGoals>().eq("user_id", userId).eq("is_flag", 0)
                .ne("is_notification",2));
        Map<String, List<FitnessGoals>> groupedByProgress = fitnessGoalsList.stream()
                .filter(goal -> goal.getGoalValue() != 0)
                .collect(Collectors.groupingBy(
                        goal -> {
                            double progress = (goal.getActualValue() / goal.getGoalValue()) * 100;
                            return progress == 100 ? "completed" : (progress >= 90 ? "close" : "other");
                        }
                ));

        // 发送通知
        if (groupedByProgress.containsKey("completed")) {
//            FitnessGoals fitnessGoals = fitnessGoalsMapper.selectOne(new QueryWrapper<FitnessGoals>().eq("progress",100).eq("user_id",userId).eq("is_flag",0)
//                    .eq("is_notification",1));
//            fitnessGoals.setIsNotification(2);
//            fitnessGoalsMapper.update(fitnessGoals,new QueryWrapper<FitnessGoals>().eq("user_id",userId)
//                    .eq("is_flag",0).eq("is_notification",1).eq("progress",100).eq("goal_id",goalId));
//            if(fitnessGoals.getIsNotification()==2){
//                Notifications notifications = new Notifications();
//                notifications.setUserId(userId);
//                notifications.setMessage(MESSAGE_COMPLETED);
//                notifications.setType("目标完成");
//                notifications.setNotificationTime(LocalDateTime.now());
//                notificationsMapper.insert(notifications);
//            }
            try {
                // 构建查询条件
                QueryWrapper<FitnessGoals> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("progress", 100)
                        .eq("user_id", userId)
                        .eq("is_flag", 0)
                        .eq("is_notification", 1);

                // 查询满足条件的目标列表
                List<FitnessGoals> fitnessGoalsList1 = fitnessGoalsMapper.selectList(queryWrapper);

                // 提取目标ID列表
                List<Integer> idList = fitnessGoalsList1.stream()
                        .map(FitnessGoals::getGoalId)
                        .collect(Collectors.toList());
                log.info("completed: idList = " + idList);
                if (!idList.isEmpty()) {
                    // 更新目标的通知状态
                    updateNotificationStatus(idList,2);

                    // 插入通知
                    insertNotifications(fitnessGoalsList1, userId,MESSAGE_COMPLETED,"目标完成");
                }

            } catch (Exception e) {
                // 处理异常，例如记录日志或抛出自定义异常
                log.error("更新目标和发送通知失败", e);
            }
        }

        if (groupedByProgress.containsKey("close")) {
//            FitnessGoals fitnessGoals = fitnessGoalsMapper.selectOne(new QueryWrapper<FitnessGoals>().gt("progress",90).eq("user_id",userId).eq("is_flag",0)
//                    .eq("is_notification",0).or().eq("progress",90));

//            fitnessGoals.setIsNotification(1);
//            fitnessGoalsMapper.update(fitnessGoals,new QueryWrapper<FitnessGoals>().eq("user_id",userId).eq("is_flag",0)
//                    .eq("is_notification",0).gt("progress",90).eq("goal_id",goalId).or().eq("progress",90));
//            if(fitnessGoals.getIsNotification()==1){
//                Notifications notifications = new Notifications();
//                notifications.setUserId(userId);
//                notifications.setMessage(MESSAGE_CLOSE);
//                notifications.setType("接近目标");
//                notifications.setNotificationTime(LocalDateTime.now());
//                notificationsMapper.insert(notifications);
//            }

            try {
                // 构建查询条件
                QueryWrapper<FitnessGoals> queryWrapper = new QueryWrapper<>();
                queryWrapper.gt("progress", 90)
                        .eq("user_id", userId)
                        .eq("is_flag", 0)
                        .eq("is_notification", 0);


                // 查询满足条件的目标列表
                List<FitnessGoals> fitnessGoalsList2 = fitnessGoalsMapper.selectList(queryWrapper);

                // 提取目标ID列表
                List<Integer> idList = fitnessGoalsList2.stream()
                        .map(FitnessGoals::getGoalId)
                        .collect(Collectors.toList());
                log.info("close: idList = " + idList);
                if (!idList.isEmpty()) {
                    // 更新目标的通知状态
                    updateNotificationStatus(idList,1);

                    // 插入通知
                    insertNotifications(fitnessGoalsList2, userId,MESSAGE_CLOSE,"接近目标");
                }

            } catch (Exception e) {
                // 处理异常，例如记录日志或抛出自定义异常
                log.error("更新目标和发送通知失败", e);
            }
        }
    }

    private void insertNotifications(List<FitnessGoals> fitnessGoalsList, Integer userId,String message,String type) {
        List<Notifications> notificationsList = fitnessGoalsList.stream()
                .map(goal -> {
                    Notifications notification = new Notifications();
                    notification.setUserId(userId);
                    notification.setMessage(message);
                    notification.setType(type);
                    notification.setNotificationTime(LocalDateTime.now());
                    return notification;
                })
                .collect(Collectors.toList());

        // 批量插入通知
        notificationsMapper.saveBatch(notificationsList);
    }

    private void updateNotificationStatus(List<Integer> idList,int value)  {
        FitnessGoals fitnessGoals = new FitnessGoals();
        fitnessGoals.setIsNotification(value);
        fitnessGoalsMapper.update(fitnessGoals, new UpdateWrapper<FitnessGoals>().in("goal_id", idList));
    }
    @Override
    public void deleteNotifications(Integer id) {
        notificationsMapper.deleteById(id);
    }
}




